﻿using AutoMapper;
using banyuetan_2_0.Common.Helper;
using banyuetan_2_0.Controllers;
using banyuetan_2_0.IServices;
using banyuetan_2_0.Model;
using banyuetan_2_0.Model.Models;
using banyuetan_2_0.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace banyuetan_2_0.Api.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize(Permissions.Name)]
    public class CategoryController : BaseApiCpntroller
    {
        readonly ISysUserInfoServices _sysUserInfoServices;
        readonly ICategoryService _categoryService;
        private readonly IMapper mapper;

        public CategoryController(ISysUserInfoServices sysUserInfoServices, ICategoryService categoryService,IMapper mapper)
        {
            _sysUserInfoServices = sysUserInfoServices;
            _categoryService = categoryService;
            this.mapper = mapper;
        }

        #region Get(所有的Get方法都不加权限)
        /// <summary>
        /// 计数
        /// </summary>
        /// <returns></returns>
        [HttpGet("count")]
        public async Task<MessageModel<int>> GetCountAsync()
        {
            return Success<int>((await _categoryService.Query(c => c.cIsDeleted == false)).Count());
        }
        
        /// <summary>
        /// 统计某一个父亲分类下有多少个子分类
        /// </summary>
        /// <returns></returns>
        [HttpGet("countbypid/{pid}")]
        public async Task<MessageModel<int>> GetCountByParentIdAsync(int pid)
        {
            return Success<int>((await _categoryService.Query(c => c.cIsDeleted == false && c.cParentId == pid)).Count());
        }

        /// <summary>
        /// 拿到全部的指定pid的分类，默认pid为0
        /// </summary>
        /// <returns></returns>
        [HttpGet("{pid}")]
        public async Task<MessageModel<List<CategoryViewModel>>> GetByParentIdAsync(int pid = 0)
        {
            var result = (await _categoryService.Query(c => c.cParentId == pid&&c.cIsDeleted==false));
            //添加hasChildren属性
            var data = mapper.Map<List<CategoryViewModel>>(result);
            foreach (var item in data)
            {
                //查找是否有内容的pid等于item的id，如果有就给true
                if ((await GetCountByParentIdAsync(item.cID)).response > 0)
                {
                    item.hasChildren = true;
                }
            }
            return Success<List<CategoryViewModel>>(data);
        }


        /// <summary>
        /// 分页拿到指定pid的分类，默认pid为0
        /// </summary>
        /// <returns></returns>
        [HttpGet("page/{pid}")]
        public async Task<MessageModel<PageModel<CategoryViewModel>>> GetByParentIdPagedAsync([FromRoute]int pid = 0, [FromQuery]int pageIndex = 1, [FromQuery]int pageSize = 10)
        {
            var result = await _categoryService.QueryPage(c=>c.cParentId == pid && c.cIsDeleted == false, pageIndex, pageSize);
            //var pageModel= new PageModel<CategoryViewModel>() { data = mapper.Map<List<CategoryViewModel>>(result.data), dataCount = result.dataCount, page = result.page, pageCount = result.pageCount, PageSize = result.PageSize };
            //添加hasChildren属性
            var data = mapper.Map<List<CategoryViewModel>>(result.data);
            foreach (var item in data)
            {
                //查找是否有内容的pid等于item的id，如果有就给true
                if ((await GetCountByParentIdAsync(item.cID)).response>0)
                {
                    item.hasChildren = true;
                }
            }
            return SuccessPage<CategoryViewModel>(pageIndex, result.dataCount,data, result.pageCount);
        }

        /// <summary>
        /// 关键字搜索并且分页拿到包含指定内容的分类，默认keyword为"",此时就不用考虑pid的问题，拿到的内容会自动返回haschildren信息，要查询再用pid进行二级查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<MessageModel<PageModel<CategoryViewModel>>> GetByKeywordPagedAsync([FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 10, [FromQuery] string keyword = "")
        {
            Expression<Func<Category, bool>> expression = c => c.cName.ToLower().Contains(keyword) && c.cIsDeleted == false;
            if (string.IsNullOrEmpty(keyword) || string.IsNullOrWhiteSpace(keyword))
            {
                keyword = "";
            }

            if (keyword != "")
            {
                expression= c => c.cName.ToLower().Contains(keyword) && c.cIsDeleted == false;
            }
            else
            {
                expression=c => c.cIsDeleted == false;
            }

            
            var result = await _categoryService.QueryPage(expression, pageIndex, pageSize);
            //var pageModel= new PageModel<CategoryViewModel>() { data = mapper.Map<List<CategoryViewModel>>(result.data), dataCount = result.dataCount, page = result.page, pageCount = result.pageCount, PageSize = result.PageSize };
            //添加hasChildren属性
            var data = mapper.Map<List<CategoryViewModel>>(result.data);
            foreach (var item in data)
            {
                //查找是否有内容的pid等于item的id，如果有就给true
                if ((await GetCountByParentIdAsync(item.cID)).response > 0)
                {
                    item.hasChildren = true;
                }
            }
            return SuccessPage<CategoryViewModel>(pageIndex, result.dataCount, data, result.pageCount);
        }

        /// <summary>
        /// 拿到指定id的分类
        /// </summary>
        /// <returns></returns>
        [HttpGet("single/{id}")]
        public async Task<MessageModel<CategoryViewModel>> GetByIdAsync(int id)
        {
            var result = await _categoryService.QueryById(id);
            if (result.cIsDeleted==true||result==null)
            {
                Failed<CategoryViewModel>();
            }
            //if (result==null)
            //{
            //    return new MessageModel<CategoryViewModel>() { msg = "target not found", success = false, status = 404 };
            //}
            //return new MessageModel<CategoryViewModel>() { msg = "success", success=true,status=200,response= mapper.Map<CategoryViewModel>(result) };
            return Success<CategoryViewModel>(mapper.Map<CategoryViewModel>(result));
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpGet("tree")]
        public async Task<MessageModel<CategoryTree>> GetCategoryTree(int pid = 0)
        {
            var data = new MessageModel<CategoryTree>();

            var categories = await _categoryService.Query(d => d.cIsDeleted == false);
            var categoryTrees = (from child in categories
                                 where child.cIsDeleted == false
                                   orderby child.cID
                                   select new CategoryTree
                                   {
                                       value = child.cID,
                                       label = child.cName,
                                       Pid = child.cParentId,
                                   }).ToList();
            CategoryTree rootRoot = new CategoryTree
            {
                value = 0,
                Pid = 0, 
                label = "根节点"
            };

            //CategoryTrees = CategoryTrees.OrderBy(d => d.order).ToList();


            RecursionHelper.LoopToAppendChildrenT<CategoryTree>(categoryTrees, rootRoot);

            data.success = true;
            if (data.success)
            {
                data.response = rootRoot;
                data.msg = "获取成功";
            }

            return data;
        }

        /// <summary>
        /// 根据id获取菜单树信息
        /// </summary>
        /// <param name="cId"></param>
        /// <returns></returns>
        [HttpGet("tree/{cId}")]
        public async Task<MessageModel<string>> GetCategoryTreeById(int cId)
        {
            var data = new MessageModel<string>();
            data.success = true;
            var result = "根节点";
            var category = await _categoryService.QueryById(cId);
            if (category==null)
            {
               
                data.response = result;
                return data;
            }
            List<Category> categories = new List<Category>();
            categories.Add(category);
            while (category.cParentId != 0)
            {
                category = await _categoryService.QueryById(category.cParentId);
                categories.Add(category);
            }
            categories.Reverse();
            foreach (var item in categories)
            {
                result = result + ">>" + item.cName;
            }

            data.response = result;
            return data;
        }
        #endregion

        #region 删除

        //// <summary>
        //// 删除单个（真删除） 暂时不考虑真删除，删除前应该移除所有的外键引用，即删除所有的News
        //// </summary>
        //// <returns></returns>
        //[HttpDelete("real/{id}")]
        //public async Task<MessageModel<bool>> RealDeleteAsync(int id)
        //{
        //    //查找对应的内容
        //    var result = await _categoryService.QueryById(id);
        //    //删除对应的内容
        //    if (result==null)
        //    {
        //        if (await _categoryService.DeleteById(result.cID))
        //        {
        //            return Success<bool>(true);
        //        }
        //    }
        //    return Failed<bool>();
        //}

        ///// <summary>
        ///// 删除多个（真删除）
        ///// </summary>
        ///// <returns></returns>
        //[HttpDelete("real")]
        //public async Task<MessageModel<bool>> RealDeleteMultipleAsync(object[] ids)
        //{
        //    //查找对应的内容
        //    //var result = await _categoryService.QueryById(ids);
        //    //删除对应的内容
        //        if (await _categoryService.DeleteByIds(ids))
        //        {
        //            return Success<bool>(true);
        //        }
        //    return Failed<bool>();
        //}

        /// <summary>
        /// 删除单个（假删除）
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        [Authorize(Permissions.Name)]
        public async Task<MessageModel<bool>> DeleteAsync(int id)
        {
            //查找对应的内容
            var result = await _categoryService.QueryById(id);
            if (result==null)
            {
                return Failed<bool>("未找到指定内容，删除失败！");
            }
            result.cIsDeleted = true;
            //删除对应的内容
            //if (result == null)
            //{
            //    if (await _categoryService.DeleteById(result.cID))
            //    {
            //        return Success<bool>(true);
            //    }
            //}
            if (await _categoryService.Update(result))
            {
                //如果删除一个上级，同时要将其的所有下级一并删除
                var list = (await GetByParentIdAsync(result.cID)).response;
                try
                {
                    foreach (var item in list)
                    {
                        item.cIsDeleted = true;
                        await _categoryService.Update(item);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return  Success<bool>(true);
            }
            return Failed<bool>("服务器错误，删除失败！");
        }

        /// <summary>
        /// 删除多个（假删除）
        /// </summary>
        /// <returns></returns>
        [HttpDelete("multiple")]
        [Authorize(Permissions.Name)]
        public async Task<MessageModel<bool>> DeleteMultipleAsync(object[] ids)
        {
            //查找对应的内容
            //var result = await _categoryService.QueryById(ids);
            //删除对应的内容
            //if (await _categoryService.DeleteByIds(ids))
            //{
            //    return Success<bool>(true);
            //}
            bool result = false;
            var list = await _categoryService.QueryByIDs(ids);
            foreach (var item in list)
            {
                result =result&&( await DeleteAsync(item.cID)).success;
            }
            return result?Success<bool>(result): Failed<bool>();
        }

        #endregion

        #region 新增

        /// <summary>
        /// 新增单个
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Permissions.Name)]
        public async Task<MessageModel<int>> AddAsync([FromBody]CategoryViewModel categoryViewModel)
        {
            Category category = mapper.Map<Category>(categoryViewModel);
            int result=await _categoryService.Add(category);
            //成功之后拿到新的内容再返回级前端？其实不用返回，成功后让列表更新即可
            return result > 0 ? Success<int>(result):Failed<int>();
        }

        #endregion

        #region 修改

        /// <summary>
        /// 修改单个
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [Authorize(Permissions.Name)]
        public async Task<MessageModel<bool>> UpdateAsync([FromBody] CategoryViewModel categoryViewModel)
        {
            Category category = mapper.Map<Category>(categoryViewModel);
            bool result = await _categoryService.Update(category);
            //成功之后拿到新的内容再返回级前端？其实不用返回，成功后让列表更新即可
            return result ? Success<bool>(result) : Failed<bool>();
        }

        #endregion


    }
}
